import type { IRouteItem } from '@/routers/routerConfig';
import type { TabsProps } from 'antd';
import { message, Tabs } from 'antd';
import { isEmpty } from 'lodash-es';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

type IMapVal = {
  key: string;
  label: string;
};

interface ICusTabItem extends IMapVal {
  disabled?: boolean;
  fullPath?: string;
}

function TopTabs(props: { routes: IRouteItem[] }) {
  const { routes } = props;
  // 用作dom更新
  const [activeKey, setActiveKey] = useState<string>();
  const [tabItems, setTabItems] = useState<ICusTabItem[]>([]);

  // 用作计算
  const activeKeyRef = useRef<string>();
  const tabItemsRef = useRef<ICusTabItem[]>([]);

  const location = useLocation();
  const navigator = useNavigate();

  const routerMap: Map<string, IMapVal> = useMemo(() => {
    // console.log('--routerMap--routes---:', routes);
    const tempRouterMap = new Map<string, IMapVal>();

    function recursionRouter(routesParam: IRouteItem[], routerMapParam: Map<string, IMapVal>) {
      for (let i = 0; i < routesParam.length; i++) {
        const { key, label, children } = routesParam[i];
        if (isEmpty(routerMapParam.get(key))) {
          routerMapParam.set(key, { key, label: label! });
        }
        if (!isEmpty(children)) {
          recursionRouter(children!, routerMapParam);
        }
      }
    }
    recursionRouter(routes, tempRouterMap);
    // console.log('--tempRouterMap---:', tempRouterMap);
    return tempRouterMap;
  }, []);

  useEffect(() => {
    console.log('--TopTabs--location.pathname --:', location.pathname);
    if (location.pathname && location.pathname !== '/') {
      const lastPath = location.pathname.split('/').pop();
      if (lastPath !== activeKeyRef.current) {
        const tabItemsIndex = tabItemsRef.current.findIndex((item) => item.key === lastPath);
        const routerItem = routerMap.get(lastPath!);
        // add
        if ((tabItemsIndex === undefined || tabItemsIndex < 0) && !isEmpty(routerItem)) {
          tabItemsRef.current?.push({ ...routerItem, fullPath: location.pathname });
          // 只有一个时不许删除
          tabItemsRef.current[0].disabled = tabItemsRef.current.length <= 1 ? true : false;
          setTabItems([...tabItemsRef.current]);
        }
        activeKeyRef.current = lastPath;
        setActiveKey(lastPath);
      }
    }
  }, [location.pathname, routerMap]);

  // 切换
  const onTabChange: TabsProps['onChange'] = (activeKey) => {
    // console.log('--切换是不是也触发了---');
    activeKeyRef.current = activeKey;
    setActiveKey(activeKey);
    const curItem = tabItemsRef.current.find((item: ICusTabItem) => item.key === activeKey);
    navigator(curItem!.fullPath!);
  };

  // 删除
  const onTabEdit: TabsProps['onEdit'] = (key, action) => {
    if (action === 'remove') {
      if (tabItemsRef.current.length <= 1) return;
      const curItemIndex = tabItemsRef.current.findIndex((item: ICusTabItem) => item.key === key);
      if (curItemIndex < 0) {
        return message.error('未找到 curItem');
      }
      const { fullPath: prevFullPath, key: prevKey } =
        tabItemsRef.current[curItemIndex === 0 ? curItemIndex + 1 : curItemIndex - 1];
      activeKeyRef.current = prevKey;
      setActiveKey(prevKey);
      tabItemsRef.current.splice(curItemIndex, 1);
      // 只有一个时不许删除
      tabItemsRef.current[0].disabled = tabItemsRef.current.length <= 1 ? true : false;
      setTabItems([...tabItemsRef.current]);
      navigator(prevFullPath!);
    }
  };

  return (
    <Tabs
      className="ym-workarea"
      type="editable-card"
      hideAdd
      size="small"
      onChange={onTabChange}
      activeKey={activeKey}
      onEdit={onTabEdit}
      items={tabItems}
    ></Tabs>
  );
}

export default TopTabs;
